package rahmath.sharif.docrypt;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import javax.crypto.Cipher;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.entity.Vault;
import rahmath.sharif.docrypt.util.Docrypt;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ManageAttachmentActivity extends Activity implements
		DocryptConstants, DocryptInterface {
	private String destinationDirectory;
	private ProgressDialog progressDialog;

	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	public Activity getActivity() {
		return this;
	}

	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_attachment);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		final Bundle bundle = getIntent().getExtras();
		final Vault vault = DocryptUtil.getVaultFromSD(bundle
				.getString(VAULT_FILE_NAME));
		final String dataKey = bundle.getString(DATA_KEY);
		final String attachmentName = bundle.getString(ATTACHMENT_KEY);
		((EditText) findViewById(R.id.editTextFileName))
				.setText(attachmentName);
		File file = new File(
				DocryptUtil.getDocryptDir(DOCRYPT_DATAS_ATTACHMENTS), vault
						.getDatas().get(dataKey).getAttachments()
						.get(attachmentName));
		long timeStamp = file.lastModified();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT,
				Locale.getDefault());
		((EditText) findViewById(R.id.editTextCreatedTime)).setText(sdf
				.format(new Date(timeStamp)));
		long size = file.length();
		if ((size / 1024L) == 0) {
			((EditText) findViewById(R.id.editTextFileSize)).setText(size
					+ " B");
		} else if ((size / 1048576L) == 0) {
			((EditText) findViewById(R.id.editTextFileSize)).setText(size
					/ 1024L + " KB");
		} else {
			((EditText) findViewById(R.id.editTextFileSize)).setText(size
					/ 1048576L + " MB");
		}
		destinationDirectory = vault.getDatas().get(dataKey).getExtractFolder();
		((EditText) findViewById(R.id.editTextExtractFolderPath))
				.setText(destinationDirectory);

	}

	public void chooseDirectory(View view) {
		Intent intentChooseFile = new Intent(this, Explorer.class);
		intentChooseFile.putExtra(INTENT_EXTRA_CHOOSE, DIRECTORY);
		intentChooseFile.putExtra(INTENT_EXTRA_FILE_PATH,
				((EditText) findViewById(R.id.editTextExtractFolderPath))
						.getText().toString());
		startActivityForResult(intentChooseFile, INTENT_CHOOSE_DIRECTORY);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case INTENT_CHOOSE_DIRECTORY:
			if (resultCode == Activity.RESULT_OK) {
				destinationDirectory = data
						.getStringExtra(INTENT_EXTRA_CHOOSEN_PATH);
				((TextView) findViewById(R.id.editTextExtractFolderPath))
						.setText(destinationDirectory);
				Bundle bundle = getIntent().getExtras();
				final Vault vault = DocryptUtil.getVaultFromSD(bundle
						.getString(VAULT_FILE_NAME));
				vault.getDatas().get(bundle.getString(DATA_KEY))
						.setExtractFolder(destinationDirectory);
				DocryptUtil.putVaultToSD(vault);
			}
			break;
		}
	}

	public void extract(View view) {
		Bundle bundle = getIntent().getExtras();
		String password = bundle.getString(VAULT_PASSWORD);
		final Vault vault = DocryptUtil.getVaultFromSD(bundle
				.getString(VAULT_FILE_NAME));
		File sourceFile = new File(
				DocryptUtil.getDocryptDir(DOCRYPT_DATAS_ATTACHMENTS), vault
						.getDatas().get(bundle.getString(DATA_KEY))
						.getAttachments().get(bundle.getString(ATTACHMENT_KEY)));
		if (sourceFile.length() > DocryptUtil.getSpaceAvailable()) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.spaceNotAvailable), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		File derivedFile = new File(new File(destinationDirectory),
				bundle.getString(ATTACHMENT_KEY));
		final Docrypt decrypter = new Docrypt(this, password, sourceFile,
				derivedFile, Cipher.DECRYPT_MODE);
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(getString(R.string.decrypting));
		progressDialog.setIndeterminate(false);
		progressDialog.setMax(100);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						decrypter.cancel(true);
						dialog.dismiss();
					}
				});
		progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				return true;
			}
		});
		decrypter.execute((String[]) null);

	}

	public void delete(View view) {
		DialogInterface.OnClickListener confirmDialog = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					Bundle bundle = getIntent().getExtras();
					Vault vault = DocryptUtil.getVaultFromSD(bundle
							.getString(VAULT_FILE_NAME));
					HashMap<String, String> attachments = vault.getDatas()
							.get(bundle.getString(DATA_KEY)).getAttachments();
					boolean success = new File(
							DocryptUtil
									.getDocryptDir(DOCRYPT_DATAS_ATTACHMENTS),
							attachments.get(bundle.getString(ATTACHMENT_KEY)))
							.delete();
					attachments.remove(bundle.getString(ATTACHMENT_KEY));
					DocryptUtil.putVaultToSD(vault);
					if (success) {
						Toast.makeText(
								getApplicationContext(),
								getString(R.string.attachmentDeletionSuccessful),
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getApplicationContext(),
								getString(R.string.attachmentDeletionFailed),
								Toast.LENGTH_SHORT).show();
					}
					finish();
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					dialog.dismiss();
					break;
				}
			}
		};
		new AlertDialog.Builder(ManageAttachmentActivity.this)
				.setCancelable(false)
				.setTitle("Confirm Delete!")
				.setMessage(
						"Attachment Name : "
								+ getIntent().getExtras().getString(
										ATTACHMENT_KEY))
				.setPositiveButton("Delete", confirmDialog)
				.setNegativeButton("Cancel", confirmDialog).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_manage_attachment, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.lockVault:
			Intent vaultsIntent = new Intent(this, VaultsActivity.class);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(vaultsIntent);
			return true;
		case R.id.deleteData:
			final Vault vaultDataDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteData = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						String dataKey = getIntent().getExtras().getString(
								DATA_KEY);
						boolean success1 = DocryptUtil.deleteDataFromSD(
								vaultDataDel, dataKey);
						vaultDataDel.getDatas().remove(dataKey);
						boolean success2 = DocryptUtil
								.putVaultToSD(vaultDataDel);
						if (success1 && success2) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent datasIntent = new Intent(
									ManageAttachmentActivity.this,
									DatasActivity.class);
							datasIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							datasIntent
									.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							datasIntent.putExtra(VAULT_FILE_NAME,
									vaultDataDel.getVaultFileName());
							startActivity(datasIntent);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(ManageAttachmentActivity.this)
					.setCancelable(false)
					.setTitle("Confirm Delete!")
					.setMessage(
							"Data : "
									+ vaultDataDel
											.getDatas()
											.get(getIntent().getExtras()
													.getString(DATA_KEY))
											.getName())
					.setPositiveButton("Delete", confirmDialogDeleteData)
					.setNegativeButton("Cancel", confirmDialogDeleteData)
					.show();
			return true;
		case R.id.deleteVault:
			final Vault vaultDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteVault = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						boolean success = DocryptUtil
								.deleteVaultFromSD(vaultDel);
						if (success) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent vaultsIntent = new Intent(
									ManageAttachmentActivity.this,
									VaultsActivity.class);
							vaultsIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							vaultsIntent
									.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(vaultsIntent);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(ManageAttachmentActivity.this)
					.setCancelable(false).setTitle("Confirm Delete!")
					.setMessage("Vault : " + vaultDel.getName())
					.setPositiveButton("Delete", confirmDialogDeleteVault)
					.setNegativeButton("Cancel", confirmDialogDeleteVault)
					.show();
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
